<?php
declare(strict_types=1);

namespace App\Console\Commands\Tasks;


use Illuminate\Console\Command;

class ClearCacheCommand extends Command
{
    //命令名  房间code:修改类型
    protected $signature = 'script:clear_cache {arg?}';

    //命令描述:修复房间排行榜
    protected $description = 'clear redis cache';

    public function __construct()
    {
        parent::__construct();
    }

    //业务处理
    public function handle()
    {
        $arg = $this->argument("arg");
        if($arg == "*"){
            $this->errorTips("危险操作，不允许清除: {$arg}");
        }
        if(empty($arg)){
            return $this->errorTips("请选择要清除的key; 命令格式: php artisan script:clear_cache KEY名");
        }
        $keys = app("redis")->keys($arg);
        // $keys = app('redis')->connection('game')->keys($arg);
        if(empty($keys)){
            return $this->infoTips("KEY: {$arg}不存在");
        }
        $result = app("redis")->del($keys);
        // $result = app('redis')->connection('game')->del($keys);;
        $this->infoTips("数量: $result");
        $this->infoTips("缓存:" . json_encode($keys));
        $this->successTips("清除成功");
    }

    public function infoTips(string $message)
    {
        echo "\033[33m [INFO]\033[0m    {$message}" . PHP_EOL;
        return true;
    }

    public function errorTips(string $message)
    {
        echo "\033[31m [ERROR]\033[0m   {$message}" . PHP_EOL;
        return false;
    }

    public function successTips(string $message)
    {
        echo "\033[32m [SUCCESS]\033[0m {$message}" . PHP_EOL;
        return true;
    }
}